include('shared.lua');

ENT.menu = {};
ENT.block = {};

function ENT:Initialize()
	self.firstThink = true;
end

function ENT:Draw()
	if(self.block) then 
		if(self.block.Render) then 
			local b = self.block:Render();
			if(b) then self.Entity:DrawModel(); return;
			else return; end
		end
	end
	self.Entity:DrawModel();
end

function ENT:MakePanel()
	local m = self.menu;
	if(m.frame) then
		if(m.frame:IsValid()) then
			return;
		else
			m.frame = vgui.Create("DFrame");
			m.frame:SetName("bh_ent_panel");
		end
	else
		m.frame = vgui.Create("DFrame");
		m.frame:SetName("bh_ent_panel");
	end
	
	local height = surface.ScreenHeight();
	local width = surface.ScreenWidth();
	
	local frameX = width/10;
	local frameY = height-height/3;
	local frameWidth = width-2*frameX;
	local frameHeight = height-frameY;
	
	m.frame:SetPos(frameX, frameY);
	m.frame:SetSize(frameWidth, frameHeight);
	m.frame:SetTitle( "Block Managment" );
	m.frame:SetVisible(true);
	m.frame:MakePopup();
	
	local health = self.Entity:GetNetworkedInt("blockHealth");
	local healthLabel = vgui.Create("DLabel");
	healthLabel:SetParent(m.frame);
	healthLabel:SetPos(5,20);
	healthLabel:SetSize(frameWidth/2,20);
	healthLabel:SetText("Health: " .. health);
	
	local blockCategory = vgui.Create("DCollapsibleCategory");
	blockCategory:SetLabel("Block Specific Options");
	blockCategory:SetParent(m.frame);
	blockCategory:SetPos(5,50);
	blockCategory:SetSize(frameWidth-10, frameHeight-55);
	blockCategory:SetPadding( 10 );
	
	local blockPanel = vgui.Create("DForm");
	blockCategory:SetContents(blockPanel);
	blockPanel:SetSize(frameWidth-10, frameHeight-55);
	if(!self.block:DrawCPanel(blockPanel)) then
		blockPanel:Remove();
		blockCategory:Remove();
		return;
	else
		blockPanel:InvalidateLayout(true);
		blockCategory:InvalidateLayout(true);
	end;
end

function ENT:SetBlock(b)
	self.block = deepcopy(self.Blocks[b]);
	self.block.SENT = self;
	self.block:Init();

end

function ENT:SendServerMessage(cmd)
	LocalPlayer():ConCommand("bhserver " .. cmd .. " " ..self.Entity:EntIndex() .. "\n");
end

function GetBlockSet( args )
	local ent = ents.GetByIndex(args:ReadLong());
	ent:SetBlock( args:ReadString());
end
usermessage.Hook("SendClientBlock", GetBlockSet);

function GetTeamSet( args )
	local ent = ents.GetByIndex(args:ReadLong());
	ent.block.Team = args:ReadLong();
end
usermessage.Hook("SendClientTeam", GetTeamSet);

function ShowCPanel( args )
	local ent = ents.GetByIndex(args:ReadLong());
	ent:MakePanel();
end
usermessage.Hook("OpenClientPanel", ShowCPanel);

function ENT:Think()
	if(self.firstThink) then
		//Request a server update
		LocalPlayer():ConCommand("bhserver update " .. self.Entity:EntIndex());
		self.firstThink = false;
	end
	
	self.Entity:NextThink(CurTime() + 0.5);
	return true;
end 